// pages/reviewRecord/grammarwork/grammarwork.js
const app = getApp();
const httpUtils = require('../../../utils/httpUtils.js');
const CryptoJS = require('../../../utils/CryptoJS.js');
let tool = require('../../../utils/tool.js');
const audio = require('../../../utils/audio.js');
//  正在录音的下标
let recordingIndex = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    grammarlist: [],
    type: 4, //	 4语法 
    page: 1,
    pageSize: 200,
    reviewLen: 0, //复习的长度
    selNums: {},
    date: '',
    innerAudioContext: new Object(),
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    audioTotalsrc: "https://vediosource.oss-cn-beijing.aliyuncs.com/grammar/US/voice/",
    hasreview: 0, //0未复习，1已提交复习
    has_read: 0, //0无语音识别读一遍，1有读一遍
    has_picture: 1,  //0无图片作业   1有图片作业
    fileList: [], //上传图片列表
    btnPlayStatus: [], //语音识别的三个按钮的状态
    showRecordModal: false, //正在识别的弹窗
    originalStr: "", //原字符串即句子（打分时用）
    task_id: '', //任务id
    sort: '11', //类别  10写一遍，11读一遍
    cloudPath: [],
    tempFiles: "",
    isUploadComplet: 0, //0图片未上传完，1已上传完
    userAnswerList: [],
    can_submit: 1, //1 可以提交 0不可以提交
    pic: [], //图片作业数组
    flag: true, //是否显示提交成功的弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    if (options) {
      that.setData({
        task_id: options.task_id,
        sort: options.sort,
        can_submit: options.can_submit,
      })
    }
    console.log("接收到的can_submit=" + that.data.can_submit);
    //初始化audio
    that.data.innerAudioContext = wx.createInnerAudioContext();
    that.data.innerAudioContext.autoplay = false;
    that.data.innerAudioContext.loop = false;

    if (that.data.sort == 11) {
      //读一遍
      that.setData({
        has_read: 1, //0无语音识别读一遍，1有读一遍
        has_picture: 0,
      })

    } else if (that.data.sort == 10) {
      // 写一遍
      that.setData({
        has_read: 0, //0无语音识别读一遍，1有读一遍
        has_picture: 1,
      })
    }

    //获取复习的语法的句子列表
    that.getDatas();
  },

  //获取语法数据列表
  getDatas: function () {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true
    })

    httpUtils.getGrammerReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sort: that.data.sort,
      page: 1,
      size: that.data.pageSize,
    }).then((res) => {
      //假数据
      // let temparr = that.data.grammarlist;
      let temparr = res.data.lists;
      that.setData({
        grammarlist: temparr,
        pic: res.data.pic
      })

      if (that.data.has_read == 1) {
        let len = that.data.grammarlist.length;
        that.setData({
          btnPlayStatus: audio.initAudioBtn(len, len)
        })
        audio.onEnded({
          callback(data) {
            that.setData({
              btnPlayStatus: data
            })
          }
        });
      }


    });

  },


  /**
   * 点击语法的句子列表
   */
  playGrammarVoice: function (e) {
    let that = this;
    let has_read = that.data.has_read;
    let tmp = that.data.grammarlist;
    let temsentence = e.currentTarget.dataset.sentence;

    let hasClick = that.data.reviewLen;
    let idx = e.currentTarget.dataset.idx;
    console.log("idx:", idx);
    let temNum = that.data.selNums;

    var isHas = false;//是否点击过 false没有点击过
    for (var key in temNum) {//0正常样式1英文变粗 2英文变粗出中文
      if (key == temsentence) {
        if (temNum[key] < 2) {
          temNum[key]++;
        } else {
          temNum[key] = 1;
        }
        isHas = true;
      } else {
        temNum[key] = 0;
      }
    }
    if (!isHas) {
      temNum[temsentence] = 1;
    }

    that.setData({
      grammarlist: tmp,
      selNums: temNum,
      reviewLen: hasClick
    })

    if (has_read == 1) {
      that.playAudio(e);
    } else {
      that.data.innerAudioContext.stop();
      let courseid = e.currentTarget.dataset.courseid + "";
      let chapterid = e.currentTarget.dataset.chapterid + "";
      let sentenceid = e.currentTarget.dataset.id + "";
      let idstr = courseid + chapterid + sentenceid;
      let encodeStr = CryptoJS.SHA256(idstr).toString();
      that.data.innerAudioContext.src = that.data.audioTotalsrc + encodeStr + ".wav"
      console.log("videosrc:" + that.data.innerAudioContext.src)
      that.data.innerAudioContext.play();
    }


  },

  // 播放音频
  playAudio: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    console.log("type=" + type + ",index=" + index)
    let audiosrc = e.currentTarget.dataset.audiosrc;
    
    if (type == 0) {
      let courseid = e.currentTarget.dataset.courseid + "";
      let chapterid = e.currentTarget.dataset.chapterid + "";
      let sentenceid = e.currentTarget.dataset.id + "";
      let idstr = courseid + chapterid + sentenceid;
      console.log("idstr:" + idstr);
      let encodeStr = CryptoJS.SHA256(idstr).toString();
      audiosrc = that.data.audioTotalsrc + encodeStr + ".wav"
      console.log("audiosrc="+audiosrc)
    }

    audio.play({
      type: type,
      index: index,
      audiosrc: audiosrc,
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });


  },

  //  录音并打分
  recordScore: function (event) {
    var that = this;
    recordingIndex = event.currentTarget.dataset.index;
    audio.stop({
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });

    that.setData({
      showRecordModal: true,
      originalStr: event.currentTarget.dataset.originalstr
    });
    console.log("originalStr:" + that.data.originalStr)
  },

  // 录音成功
  recordSuccess: function (res) {
    var that = this;
    console.log("录音成功" + JSON.stringify(res))
    that.setData({
      showRecordModal: false,
    });
    let score = res.detail.score;
    console.log("score=" + score)
    let tempFilePath = res.detail.tempFilePath;
    if (score < 0) {
      wx.showToast({
        title: '没有听清~',
        icon: 'none',
        duration: 2000
      });
    } else {
      let questData = that.data.grammarlist;
      questData[recordingIndex].score = score;
      questData[recordingIndex].user_per_voice = tempFilePath;
      that.setData({
        grammarlist: questData
      })

      let bodyParam = {
        access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
        type: tempFilePath,
      }
      let rs = tool.getSign(bodyParam, getApp().globalData.key);
      let tempurl = getApp().globalData.apiURL + 'common/upload?sign=' + rs.sign;
      console.log(tempurl)
      wx.uploadFile({
        url: tempurl,
        filePath: tempFilePath,
        name: 'file',
        formData: {
          'word':that.data.grammarlist[recordingIndex].id,
          'sub_vedio': tempFilePath,
          'type':'wx_voice',
        },
        success(res) {
          console.log("录音上传成功")
          let result = JSON.parse(res.data);
          let path = result.data.path;
          console.log(path)
          let userAnswerList = that.data.userAnswerList;
          let uanswer = new Object();
          uanswer['id'] = that.data.grammarlist[recordingIndex].id;
          uanswer['voice'] = path;
          uanswer['score'] = score;
          userAnswerList.push(uanswer);
          that.setData({
            userAnswerList: userAnswerList
          })

        },

      })

    }
  },

  // 上传文件后
  afterRead(event) {
    let that = this;
    let fileList = that.data.fileList;
    const { file } = event.detail;
    console.log(file)

    that.setData({
      fileList: fileList.concat(file)
    })
    console.log("fileList" + JSON.stringify(that.data.fileList));
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    //上传文件
    var successUp = 0; //成功个数
    var failUp = 0; //失败个数
    var length = file.length; //总共个数
    var i = 0; //第几个
    console.log("that.data.fileList.length=" + length)
    that.uploadFilePromise(file, successUp, failUp, i, length);


  },

  //删除上传的图片
  deleteimg(event) {
    let that = this;
    const { index } = event.detail;
    let fileList = that.data.fileList;
    let cloudPath=that.data.cloudPath;
    fileList.splice(index, 1);
    cloudPath.splice(index, 1);
    that.setData({
      fileList: fileList,
      cloudPath: cloudPath
    });
  },


  //提交复习
  submitReview: function (e) {
    let that = this;
    let allSentence = that.data.grammarlist;
    let answerList = that.data.userAnswerList;
    // console.log("answerList:" + JSON.stringify(answerList));
    console.log("点击提交复习按钮")

    if (that.data.has_picture == 1) {
      let fileList = that.data.fileList;
      if (!fileList.length) {
        wx.showToast({
          title: '请先上传作业图片',
          icon: 'none',
          duration: 1000
        })
        return;
      } else {
        let cloudPath = that.data.cloudPath;
        console.log("----------------cloudPath=" + JSON.stringify(cloudPath))
        let tempFiles = '';
        for (var i = 0; i < cloudPath.length; i++) {
          if (tempFiles == '') {
            tempFiles = cloudPath[i];
          } else {
            tempFiles = tempFiles + "," + cloudPath[i];
          }
        }
        console.log("-------------tempFiles=" + tempFiles)
        that.setData({
          tempFiles: tempFiles
        })
      }

    }else if(that.data.has_picture == 0){
      console.log("语音作业");
      if(that.data.showRecordModal){
        console.log("正在录音")
       return;
      }
       if(answerList.length<=0){
        wx.showToast({
          title: '请先点击条目进行录音后再提交',
          icon: 'none',
          duration: 1000
        })
        return;
       }
    }

    wx.showModal({
      title: '提示',
      content: '是否确定提交',
      success(res) {
        if (res.confirm) {
          that.setData({
            showRecordModal:false
          })
          that.submitAnswer();
        } else if (res.cancel) {
          console.log("点击了取消") 
        }
      }
    })

  },

  submitAnswer(){
    let that = this;
    let allSentence = that.data.grammarlist;
    let answerList = that.data.userAnswerList;
    let tempStudy = ''; //所有句子的id，区分
    for (var i in allSentence) {
      if (tempStudy == '') {
        tempStudy = allSentence[i].id
      } else {
        tempStudy = tempStudy + "," + allSentence[i].id;
      }
    }
    console.log("tempStudy为：", tempStudy);

    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    httpUtils.submitGrammarReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sentence_id: tempStudy,
      sort: that.data.sort,
      pic: that.data.tempFiles,
      stu_answer: JSON.stringify(answerList)
    }).then((res) => {
      wx.hideLoading();
      audio.destory();
      that.setData({
        flag: false
      })
  
    });
  },


  //点击弹窗中的完成按钮
  goComplet() {

    wx.navigateBack({
      delta: -1
    })
  },

  /**
   *  函数描述：作为上传文件时递归上传的函数体体；
    * 参数描述： 
    * filePaths是文件路径数组
    * successUp是成功上传的个数
    * failUp是上传失败的个数
    * i是文件路径数组的指标
    * length是文件路径数组的长度   
   */
  uploadFilePromise(filePaths, successUp, failUp, i, length) {
    let that = this;
    let cloudPath = that.data.cloudPath;
    wx.showLoading({
      title: '正在上传',
      mask: true
    })
    let bodyParam = {
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      type: filePaths[i].path,
    }
    let rs = tool.getSign(bodyParam, getApp().globalData.key);
    let tempurl = getApp().globalData.apiURL + 'common/upload?sign=' + rs.sign;
    console.log("tempurl:" + tempurl)
    return wx.uploadFile({
      url: tempurl,
      filePath: filePaths[i].path,
      name: 'file',
      formData: {
        'type': filePaths[i].path,
      },
      success(res) {
        successUp++;
        let result = JSON.parse(res.data);
        console.log("图片上传成功result=" + res.data);
        cloudPath.push(result.data.path);
      },
      fail(res) {
        failUp++;
      },
      complete: () => {
        wx.hideLoading();
        i++;
        if (i == length) {
          // that.showToast('总共'+successUp+'张上传成功,'+failUp+'张上传失败！');
          wx.showToast({
            title: '图片上传成功~',
            icon: 'none',
            duration: 2000
          });
          console.log('总共' + successUp + '张上传成功,' + failUp + '张上传失败！');
          that.setData({
            isUploadComplet: 1,
          })
        }
        else {  //递归调用upload函数
          that.uploadFilePromise(filePaths, successUp, failUp, i, length);
        }
      },
    })
  },


  //点击查看大图
  lookBigPic(e) {
    console.log("lookbigpic" + JSON.stringify(e))
    let that = this;
    let index = e.currentTarget.dataset.index;
    let imgUrl = that.data.pic;
    let currenturl = imgUrl[index];
    //在新界面预览样例大图
    wx.previewImage({
      current: currenturl,
      urls: imgUrl,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //停止播放
    let that = this;
    that.data.innerAudioContext.stop();
    audio.destory();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //停止播放
    let that = this;
    that.data.innerAudioContext.stop();
    audio.destory();
    that.setData({
      showRecordModal:false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})